import { Module } from '@nestjs/common';
import { ThrottlerModule } from '@nestjs/throttler';
import { TypeOrmModule } from '@nestjs/typeorm';
import { getDataSourceToken } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { APP_INTERCEPTOR, APP_GUARD } from '@nestjs/core';
import { HealthModule } from '@app/health';
import { KvBlogController } from './kv-blog.controller';
import { KvBlogService } from './kv-blog.service';
import { Post } from './entities/post.entity';
import { Blog, User, Tag, Role, Conversation, Message, Announcement, Menu } from '@app/entities';
import { PublicModule } from './public/public.module';
import { ResponseInterceptor } from '@app/common';
import { DataSource } from 'typeorm';
import { IpRateLimitGuard } from './guards/ip-rate-limit.guard';
import Redis from 'ioredis';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: ['.env.production', '.env.development', '.env'],
    }),
    // ThrottlerModule.forRootAsync({
    //   imports: [ConfigModule],
    //   useFactory: (config: ConfigService) => ({
    //     throttlers: [{
    //       ttl: Number(config.get('RATE_TTL') ?? 60),
    //       limit: Number(config.get('RATE_LIMIT') ?? 100),
    //     }],
    //   }),
    //   inject: [ConfigService],
    // }),
    ThrottlerModule.forRoot({
      throttlers: [{
        ttl: 60,
        limit: 100,
      }],
    }),
    // 使用自建 ioredis 提供器（简化依赖注入以避免版本差异问题）
    TypeOrmModule.forRootAsync({
      name: 'kv-blog',
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        type: 'mysql',
        name: 'kv-blog',
        host: configService.get('KV_BLOG_DB_HOST', 'localhost'),
        port: configService.get('KV_BLOG_DB_PORT', 3306),
        username: configService.get('KV_BLOG_DB_USERNAME', 'root'),
        password: configService.get('KV_BLOG_DB_PASSWORD', ''),
        database: configService.get('KV_BLOG_DB_NAME', 'kv_blog'),
        synchronize: configService.get('KV_BLOG_DB_SYNC', false),
        logging: configService.get('KV_BLOG_DB_LOGGING', false),
        entities: [Post, Blog, User, Tag, Role, Conversation, Message, Announcement, Menu],
        autoLoadEntities: true,
      }),
      inject: [ConfigService],
    }),
    TypeOrmModule.forFeature([Post, Blog, User, Tag, Role, Conversation, Message, Announcement, Menu], 'kv-blog'),
    PublicModule,
    HealthModule,
  ],
  controllers: [KvBlogController],
  providers: [
    KvBlogService,
    {
      provide: APP_INTERCEPTOR,
      useClass: ResponseInterceptor,
    },
    // {
    //   provide: APP_GUARD,
    //   useClass: IpRateLimitGuard,
    // },
    {
      provide: DataSource,
      useExisting: getDataSourceToken('kv-blog') as any,
    },
    // 提供 RATE_LIMIT_REDIS 供限流守卫使用
    {
      provide: 'RATE_LIMIT_REDIS',
      useFactory: (config: ConfigService) => {
        return new Redis({
          host: config.get('REDIS_HOST', 'localhost'),
          port: Number(config.get('REDIS_PORT') ?? 6379),
          password: config.get('REDIS_PASSWORD'),
          db: Number(config.get('REDIS_DB') ?? 0),
          lazyConnect: false,
        });
      },
      inject: [ConfigService],
    },
  ],
})
export class KvBlogModule { }
